/**
 * 项目名称：MSH
 * 包名称：com.mt.common.log.daoImpl
 * 文件名称：LoginLogDaoImpl.java
 */
package com.mt.system.daoImpl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.mt.system.dao.LoginLogDao;
import com.mt.system.domain.LoginLog;
import com.mt.system.dto.LogDto;
import com.mt.utils.StringUtils;


/**
 * 类名称：LoginLogDaoImpl <br>
 * 类描述： <br>
 * 创建人： 马腾 <br>
 * 创建时间：Oct 25, 2012 10:27:56 AM <br>
 */
@Repository
public class LoginLogDaoImpl implements LoginLogDao {
	
	@PersistenceContext
	protected EntityManager entityManager;

	@Override
	public LoginLog addLoginLog(LoginLog loginLog) {
		entityManager.persist(loginLog);
		return loginLog;
	}

	@Override
	public List<LoginLog> getLoginLogs(LogDto logDto, int first, int max) {
		String hql = "from LoginLog l left join fetch l.user " +
					 "where 1=1 ";
		hql += createHql(logDto);
		hql += "order by l.loginTime desc";
		Query query = entityManager.createQuery(hql);
		setQueryParameters(query , logDto);
		query.setFirstResult(first);
		query.setMaxResults(max);
		return query.getResultList();
	}

	@Override
	public int getLoginLogCount(LogDto logDto) {
		String hql = "select count(*) from LoginLog l " +
				 	 "where 1=1 ";
		hql += createHql(logDto);
		Query query = entityManager.createQuery(hql);
		setQueryParameters(query , logDto);
		Long count;
		try {
			count = (Long) query.getSingleResult();
		} catch (NoResultException e) {
			return 0;
		}
		return count == null ? 0 : count.intValue();
	}
	

	private void setQueryParameters(Query query, LogDto logDto) {
		if(logDto == null) return;
		if(logDto.getStartDate() != null && logDto.getEndDate() != null){
			query.setParameter("startDate" , logDto.getStartDate());
			query.setParameter("endDate", logDto.getEndDate());
		}
		if(!StringUtils.isEmpty(logDto.getUserName())){
			query.setParameter("userName", "%" + logDto.getUserName() + "%");
		}
		if(!StringUtils.isEmpty(logDto.getIp())){
			query.setParameter("ip", logDto.getIp() + "%");
		}
	}

	private String createHql(LogDto logDto){
		StringBuffer sb = new StringBuffer();
		if(logDto == null) return "";
		if(logDto.getStartDate() != null && logDto.getEndDate() != null){
			sb.append("and l.loginTime between :startDate and :endDate ");
		}
		if(!StringUtils.isEmpty(logDto.getUserName())){
			sb.append("and l.user.name like :userName ");
		}
		if(!StringUtils.isEmpty(logDto.getIp())){
			sb.append("and l.loginIp like :ip ");
		}
		return sb.toString();
	}
}
